import { UserApi } from '@/api/services';
import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import {
  FooterToolbar,
  ModalForm,
  PageContainer,
  ProFormText,
  ProFormSelect,
  ProTable,
} from '@ant-design/pro-components';
import { FormattedMessage, useIntl } from '@umijs/max';
import { Button, message } from 'antd';
import React, { useRef, useState } from 'react';
import type { UserDto } from '@/api/services/types';

const handleAdd = async (fields: UserDto) => {
  const hide = message.loading('正在添加');
  try {
    await UserApi.create(fields);
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败，请重试');
    return false;
  }
};

const handleUpdate = async (fields: UserDto) => {
  const hide = message.loading('正在更新');
  try {
    await UserApi.update(fields);
    hide();
    message.success('更新成功');
    return true;
  } catch (error) {
    hide();
    message.error('更新失败，请重试');
    return false;
  }
};

const handleRemove = async (selectedRows: UserDto[]) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;
  try {
    await Promise.all(selectedRows.map(row => UserApi.delete(row.id)));
    hide();
    message.success('删除成功');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

const UserList: React.FC = () => {
  const [createModalOpen, handleModalOpen] = useState(false);
  const [updateModalOpen, handleUpdateModalOpen] = useState(false);
  const [selectedRows, setSelectedRows] = useState<UserDto[]>([]);
  const [currentRow, setCurrentRow] = useState<UserDto>();
  const actionRef = useRef<ActionType>();
  const intl = useIntl();

  const columns: ProColumns<UserDto>[] = [
    {
      title: '用户名',
      dataIndex: 'userName',
      render: (dom, entity) => {
        return (
          <a onClick={() => {
            setCurrentRow(entity);
            handleUpdateModalOpen(true);
          }}>
            {dom}
          </a>
        );
      },
    },
    {
      title: '姓名',
      dataIndex: 'name',
    },
    {
      title: '邮箱',
      dataIndex: 'email',
    },
    {
      title: '状态',
      dataIndex: 'isActive',
      valueEnum: {
        true: { text: '启用', status: 'Success' },
        false: { text: '禁用', status: 'Error' },
      },
    },
    {
      title: '创建时间',
      dataIndex: 'creationTime',
      valueType: 'dateTime',
    },
    {
      title: '操作',
      valueType: 'option',
      render: (_, record) => [
        <a
          key="edit"
          onClick={() => {
            setCurrentRow(record);
            handleUpdateModalOpen(true);
          }}
        >
          编辑
        </a>,
      ],
    },
  ];

  return (
    <PageContainer>
      <ProTable<UserDto>
        headerTitle="用户列表"
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              handleModalOpen(true);
            }}
          >
            <PlusOutlined /> 新建用户
          </Button>,
        ]}
        request={async (params) => {
          const response = await UserApi.getList({
            skipCount: (params.current! - 1) * params.pageSize!,
            maxResultCount: params.pageSize,
            ...params,
          });
          return {
            data: response.data?.items,
            success: true,
            total: response.data?.totalCount,
          };
        }}
        columns={columns}
        rowSelection={{
          onChange: (_, rows) => {
            setSelectedRows(rows);
          },
        }}
      />

      {selectedRows?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择 <a style={{ fontWeight: 600 }}>{selectedRows.length}</a> 项
            </div>
          }
        >
          <Button
            onClick={async () => {
              await handleRemove(selectedRows);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
          >
            批量删除
          </Button>
        </FooterToolbar>
      )}

      <ModalForm
        title="新建用户"
        width="400px"
        open={createModalOpen}
        onOpenChange={handleModalOpen}
        onFinish={async (value) => {
          const success = await handleAdd(value as UserDto);
          if (success) {
            handleModalOpen(false);
            actionRef.current?.reload();
          }
        }}
      >
        <ProFormText
          name="userName"
          label="用户名"
          rules={[{ required: true, message: '请输入用户名' }]}
        />
        <ProFormText name="name" label="姓名" />
        <ProFormText name="email" label="邮箱" />
      </ModalForm>

      <ModalForm
        title="编辑用户"
        width="400px"
        open={updateModalOpen}
        onOpenChange={handleUpdateModalOpen}
        onFinish={async (value) => {
          const success = await handleUpdate({
            ...currentRow,
            ...value,
          } as UserDto);
          if (success) {
            handleUpdateModalOpen(false);
            setCurrentRow(undefined);
            actionRef.current?.reload();
          }
        }}
        initialValues={currentRow}
      >
        <ProFormText
          name="userName"
          label="用户名"
          rules={[{ required: true, message: '请输入用户名' }]}
        />
        <ProFormText name="name" label="姓名" />
        <ProFormText name="email" label="邮箱" />
      </ModalForm>
    </PageContainer>
  );
};

export default UserList;
